package com.delong.lease.web.app.service.impl;


import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.delong.lease.common.exception.LeaseException;
import com.delong.lease.common.redis.constant.RedisConstant;
import com.delong.lease.common.result.ResultCodeEnum;
import com.delong.lease.common.utils.JwtUtil;
import com.delong.lease.model.entity.UserInfo;
import com.delong.lease.model.enums.BaseStatus;
import com.delong.lease.web.app.mapper.UserInfoMapper;
import com.delong.lease.web.app.service.LoginService;
import com.delong.lease.web.app.service.UserInfoService;
import com.delong.lease.web.app.vo.user.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Autowired
    private Client client;
    @Autowired
    private UserInfoService userInfoService;
    @Override
    public void sendCode(String phone) throws Exception {
        //1、校验手机号不能为空
        if (ObjectUtils.isEmpty(phone)){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_PHONE_EMPTY);
        }
        //2、发送之前判断验证码是否过期
        String key = RedisConstant.APP_LOGIN_PREFIX + phone;
        Boolean hasKey = redisTemplate.hasKey(key);
        if (hasKey){
            //未过期，发送频繁
            throw new LeaseException(ResultCodeEnum.APP_SEND_SMS_TOO_OFTEN);
        }
        //3、发送短信
        String code = "";
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            code += random.nextInt(10);
        }
        SendSmsRequest smsRequest = new SendSmsRequest();
        smsRequest.setPhoneNumbers(phone);
        smsRequest.setSignName("阿里云短信测试");
        smsRequest.setTemplateCode("SMS_154950909");
        smsRequest.setTemplateParam("{\"code\":\"" + code + "\"}\n");
        client.sendSms(smsRequest);
        //4、把短信存储到redis中
        redisTemplate.opsForValue().set(key,code,RedisConstant.APP_LOGIN_CODE_RESEND_TIME_SEC, TimeUnit.SECONDS);
    }

    @Override
    public String login(LoginVo loginVo) {
        String phone = loginVo.getPhone();
        //1、校验输入框是否有验证码
        if (!StringUtils.hasText(loginVo.getCode())){
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_NOT_FOUND);
        }
        //2、校验redis中验证码是否过期
        String key = RedisConstant.APP_LOGIN_PREFIX + phone;
        String code = (String) redisTemplate.opsForValue().get(key);
        if (!StringUtils.hasText(code)){
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_EXPIRED);
        }
        //3、校验验证码与redis中是否一致
        if (!code.equals(loginVo.getCode())){
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_ERROR);
        }
        //4、判断用户是否存在，不存在则创建
        LambdaQueryWrapper<UserInfo> userInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userInfoLambdaQueryWrapper.eq(UserInfo::getPhone, phone);
        UserInfo userInfo = userInfoService.getOne(userInfoLambdaQueryWrapper);
        if (userInfo == null){
            userInfo = new UserInfo();
            userInfo.setPhone(phone);
            userInfo.setStatus(BaseStatus.ENABLE);
            userInfo.setNickname("用户"+ "-" + phone.substring(phone.length() - 4));
            userInfoService.save(userInfo);
        }
        //5、校验用户是否被禁用
        if (userInfo.getStatus().equals(BaseStatus.DISABLE)){
            throw new LeaseException(ResultCodeEnum.APP_ACCOUNT_DISABLED_ERROR);
        }
        //6、返回带有用户信息的token
        return JwtUtil.createToken(userInfo.getId(), userInfo.getPhone());
    }
}
